package test.xstream;

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class MapToVo implements Converter {

        public boolean canConvert(Class clazz) {
                return clazz.equals(HashMap.class);
        }

        public void marshal(Object value, HierarchicalStreamWriter writer,
                        MarshallingContext context) 
        {
        	AbstractMap<String,Object> map = (AbstractMap<String,Object>) value;

        	for (Entry<String,Object> entry : map.entrySet()) {
        		
                writer.startNode(entry.getKey().toString());
                writer.setValue(entry.getValue().toString());
                writer.endNode();
                
            }
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                        UnmarshallingContext context) {
        	
        	Map<String,Object> map = new HashMap<String, Object>();
        	
        	 while(reader.hasMoreChildren()) {
        	        reader.moveDown();
        	        map.put(reader.getNodeName(), reader.getValue());
        	        reader.moveUp();
        	    }
        	 
        	 return map;
        }

}